'''
Created on Apr 12, 2012

@author: dolphinigle
'''

from engine import sha1
from engine import elgamal

def CreateSigInSeparateFile(filename, output, p, g, x):
  print 'Creating sig for', filename, 'in', output
  
  fi = open(filename, 'rb')
  sha = sha1.SHA1Byte(fi.read())
  fi.close()
  
  sig = elgamal.Sign(int(p), int(g), int(x), sha)
  
  fi = open(output, 'w')
  fi.write(sig)
  fi.close()
  
  print sig
  
  return sig

def CreateSigInSameFile(filename, p, g, x):
  print 'Creating sig for', filename, 'in itself'
  
  fi = open(filename, 'rb')
  txt = fi.read()
  sha = sha1.SHA1Byte(txt)
  fi.close()
  
  sig = elgamal.Sign(int(p), int(g), int(x), sha)
  
  fi = open(filename, 'wb')
  fi.write(txt)
  fi.write(sig)
  fi.close()
  
  print sig
  
  return sig

def VerifySignatureFromFile(filename, sig_file, p, g, y):
  print 'Verifying Signature for', filename, 'whose signature is in', sig_file
  
  fi = open(sig_file, 'r')
  real_sig = fi.read()
  fi.close()
  
  fi = open(filename, 'rb')
  sha = sha1.SHA1Byte(fi.read())
  fi.close()
  print real_sig
  
  return elgamal.Verify(int(p), int(g), int(y), real_sig, sha)

def VerifySignatureInTheSameFile(filename, p, g, y):
  print 'Verifying Signature for', filename, 'whose signature is in itself'
  
  fi = open(filename, 'rb')
  txt = fi.read()
  fi.close()
  
  # Take the last 90 characters as signature
  sig = txt[-90:]
  txt = txt[:-90]
  
  sha = sha1.SHA1Byte(txt)
  print sig
  
  return elgamal.Verify(int(p), int(g), int(y), sig, sha)
